package com.glsc.ngateway.opmanage.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;

public class FileUtil {


    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 读取图片文件，转成byte[]存入mysql
     *
     * @param filePath
     * @return byte[]
     * @throws IOException
     */
    public static byte[] readByteFromFilePath(String filePath) throws IOException {
        InputStream input = null;
        byte[] byt = null;
        try {
            File file = new File(filePath);
            input = new FileInputStream(file);
            byt = new byte[input.available()];
            input.read(byt);
        } catch (Exception e) {
            log.error("异常", e);
        } finally {
            input.close();
        }
        return byt;
    }

    /**
     * 根据上传时间生成文件名
     *
     * @return
     */
    public static String gerenalFileName() {
        java.util.Date dt = new java.util.Date(System.currentTimeMillis());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(dt);
    }

    /**
     * 将Byte数组转换成文件
     *
     * @param bytes    byte数组
     * @param filePath 文件路径  如 D://test/ 最后“/”结尾
     * @param fileName 文件名
     */
    public static File fileToBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {

            file = new File(filePath + fileName);
            if (!file.getParentFile().exists()) {
                //文件夹不存在 生成
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
